package com.etown.util;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

/**
 * SQL读取公共类
 * @author AFI
 */
public class SqlMgr {
	// 存储sql的HashMap
	private static HashMap<String, String> sqlHashMap = new HashMap<String, String>();
	private static Logger log=Logger.getLogger(SqlMgr.class);
	
	static {
		try {
			//根据web.xml中配置的参数读取SQL语句配置文件
			String filePath = System.getProperty("web.home")+System.getProperty("sqlConfigFile");
			Properties properties = new Properties();
			File file = FileUtil.open(filePath);
			FileInputStream fin = new FileInputStream(file);
			properties.load(fin);
			
			// 得到所有的key
			Set<Object> keySet = properties.keySet();
			for (Iterator it = keySet.iterator(); it.hasNext();) {
				String sqlName = (String) it.next();
				String sql = properties.getProperty(sqlName);
				sqlHashMap.put(sqlName, sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private SqlMgr() {}

	/**
	 * 根据Sql名称获取相应的SQL语句
	 * @param sqlName sql名
	 * @return
	 */
	public static String getSql(String sqlName){
		String sql = null;
		try {
			for (Iterator it = sqlHashMap.entrySet().iterator(); it.hasNext();) {
				Entry entry = (Entry) it.next();
				if (sqlName.equals(entry.getKey())) {
					sql = (String) entry.getValue();
					break;
				}
			}
		} catch (Exception e) {
			log.error("获取SQL语句失败");
		}
		return sql;
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(getSql("UPDATE_USER_STATE"));
	}
}
